//
//  HotViewController.m
//  TravelFollowYourHeart
//
//  Created by 鲁万玺 on 2017/12/15.
//  Copyright © 2017年 Lwx. All rights reserved.
//

#import "HotViewController.h"
#import "HomeCollectionViewCell.h"
#import "HotRecommendCollectionReusableView.h"
#import "TravelInforViewController.h"
#import "HomeRMTJModel.h"
#import "FilmCollectionViewCell.h"
#import "TravelCollectionViewCell.h"
#import "FilmCollectionModel.h"
#import "TravelCollectionModel.h"
#import "TravelsViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <AVKit/AVKit.h>
#import "MyFilmCommentListViewController.h"
@interface HotViewController ()<UICollectionViewDataSource,UICollectionViewDelegate, HotRecommendDelegate, TravelCollectionCellDelegate>

@property (nonatomic, strong)UICollectionView *collectionView;
@property (nonatomic, assign)int rule;
@property (nonatomic, strong)HomeRMTJModel * model;
@property (nonatomic, assign)int page;
@property (nonatomic, strong)NSMutableArray * dataArr;
@property (nonatomic, strong)NSMutableArray * travelDataArra;
@property (nonatomic, strong)NSMutableArray * filmDataArra;
@property (nonatomic, assign)int topKind;//区分上面七个按钮
@property (nonatomic, assign)int bottomDiffrence;//区分下面四个按钮
@property (nonatomic, strong)FilmCollectionModel * filmModel;
@property (nonatomic, strong)TravelCollectionModel * travelModel;
@property (nonatomic, strong)TravelCollectionModelData * travelModelData;
@property (nonatomic, assign)int filmID;
@end

@implementation HotViewController(Networking)
- (void)getHotViewData{
    NSDictionary * dic = @{
                           @"rule":@(self.rule),
                           @"sign":self.sign,
                           @"page":@(1),
                           @"row":@(6),
                           @"lng":@([[NSNumber numberWithDouble:[LocationTool shareIntance].longitude] floatValue]),
                           @"lat":@([[NSNumber numberWithDouble:[LocationTool shareIntance].latitude] floatValue])
                           };
    WS(ws)
    [self showprogressHUD];
    [[HttpRequest shardWebUtil] postNetworkRequestURLString:Url(@"/index/travels") andParas:dic andTransferGottenData:^(id obj, NSError *error) {
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
        [self hiddenProgressHUD];
        if (error) {
            [[HUDHelper sharedInstance]tipMessage:obj[@"msg"]];
        }else{
            if ([obj[@"code"] integerValue] == 100000) {
                if (ws.page == 1) {
                    [ws.dataArr removeAllObjects];
                }
                ws.model = [HomeRMTJModel yy_modelWithDictionary:obj];
                [ws.dataArr addObjectsFromArray:ws.model.data];
                [ws.collectionView reloadData];
            }else{
                [[HUDHelper sharedInstance]tipMessage:obj[@"msg"]];
                [ws.dataArr removeAllObjects];
                [ws.collectionView reloadData];
            }
        }
    }];
}

- (void)getTravelInforData{
    NSDictionary *dic = @{
                          @"row":@(6),
                          @"page":@(self.page),
                          @"lng":@([LocationTool shareIntance].longitude),
                          @"lat":@([LocationTool shareIntance].latitude),
                          @"rule":@(self.rule)
                          };
    WS(ws)
    [self showprogressHUD];
    [[HttpRequest shardWebUtil]postNetworkRequestURLString:Url(@"/diary/diary") andParas:dic andTransferGottenData:^(id obj, NSError *error) {
        [ws.collectionView.mj_footer endRefreshing];
        [ws.collectionView.mj_header endRefreshing];
        [self hiddenProgressHUD];
        if (error)
        {
            
        }
        else
        {
            if ([obj[@"code"] integerValue] == 100000)
            {
                ws.travelModel = [TravelCollectionModel yy_modelWithDictionary:obj];
                if (ws.page == 1)
                {
                    [ws.travelDataArra removeAllObjects];
                }
                [ws.travelDataArra addObjectsFromArray:ws.travelModel.data];
                [ws.collectionView reloadData];
            }
        }
    }];
}

- (void)getFilmInforData{
    NSDictionary *dic = @{
                          @"row":@(6),
                          @"page":@(self.page),
                          @"lng":@([LocationTool shareIntance].longitude),
                          @"lat":@([LocationTool shareIntance].latitude),
                          @"rule":@(self.rule)
                          };
    WS(ws)
    [self showprogressHUD];
    [[HttpRequest shardWebUtil]postNetworkRequestURLString:Url(@"/diary/video") andParas:dic andTransferGottenData:^(id obj, NSError *error) {
        [ws.collectionView.mj_footer endRefreshing];
        [ws.collectionView.mj_header endRefreshing];
        [self hiddenProgressHUD];
        if (error)
        {
            
        }
        else
        {
            if ([obj[@"code"] integerValue] == 100000)
            {
                ws.filmModel = [FilmCollectionModel yy_modelWithDictionary:obj];
                if (ws.page == 1)
                {
                    [ws.filmDataArra removeAllObjects];
                }
                [ws.filmDataArra addObjectsFromArray:ws.filmModel.data];
                [ws.collectionView reloadData];
            }
        }
    }];
}

- (void)transformLikesDataWithDid:(int)did{
    NSDictionary * dic = @{
                           @"mid":[UserModel intance].member_id,
                           @"token":[UserModel intance].token,
                           @"did":@(self.filmID),
                           @"type":@(2)
                           };
    [self showprogressHUD];
    [[HttpRequest shardWebUtil] postNetworkRequestURLString:Url(@"/diary/toLike") andParas:dic andTransferGottenData:^(id obj, NSError *error) {
        [self hiddenProgressHUD];
        if (error)
        {
            [[HUDHelper sharedInstance]tipMessage:obj[@"msg"]];
        }
        else
        {
            if ([obj[@"code"] integerValue] == 100000)
            {
                [[HUDHelper sharedInstance]tipMessage:obj[@"msg"]];
            }
            else
            {
                [[HUDHelper sharedInstance]tipMessage:obj[@"msg"]];
            }
        }
    }];
}

@end

@implementation HotViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake(SCREEN_WIDTH/2 - 0.5, 200/WIDTH_5S_SCALE);
    layout.minimumLineSpacing = 0.5;
    layout.minimumInteritemSpacing = 0.5;
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT -64) collectionViewLayout:layout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor colorWithRed:220/255.0 green:220/255.0 blue:220/255.0 alpha:1];
    self.collectionView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.collectionView];
    
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([HomeCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:NSStringFromClass([HomeCollectionViewCell class]) ];
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([HotRecommendCollectionReusableView class]) bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([HotRecommendCollectionReusableView class])];
    [self.collectionView registerClass:([TravelCollectionViewCell class]) forCellWithReuseIdentifier:NSStringFromClass([TravelCollectionViewCell class])];
    [self.collectionView registerClass:([FilmCollectionViewCell class]) forCellWithReuseIdentifier:NSStringFromClass([FilmCollectionViewCell class])];
    
    self.rule = 1;
    self.dataArr = [NSMutableArray array];
    WS(ws)
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.page = 1;
        if ([self.sign intValue]<6) {
            [self getHotViewData];
        }else if ([self.sign intValue]<7){
            [self getTravelInforData];
        }else{
            [self getFilmInforData];
        }
        
    }];
    
    self.collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        ws.page ++;
//        [self getHotViewData];
        if ([self.sign intValue]<6) {
            [self getHotViewData];
        }else if ([self.sign intValue]<7){
            [self getTravelInforData];
        }else{
            [self getFilmInforData];
        }
    }];
    [self.collectionView.mj_header beginRefreshing];
    
}

- (NSMutableArray *)travelDataArra{
    if (!_travelDataArra) {
        _travelDataArra = [NSMutableArray array];
    }return _travelDataArra;
}

- (NSMutableArray *)filmDataArra{
    if (!_filmDataArra) {
        _filmDataArra = [NSMutableArray array];
    }return _filmDataArra;
}

#pragma mark - UICollectionViewDataSource,UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if ([self.sign intValue] < 6) {
        return self.dataArr.count;
    }else if ([self.sign intValue] < 7){
        return self.travelDataArra.count;
    }else{
        return self.filmDataArra.count;
    }
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.sign intValue] < 6) {
        HomeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([HomeCollectionViewCell class]) forIndexPath:indexPath];
        cell.modelData = self.dataArr[indexPath.row];
        return cell;
    }else if ([self.sign intValue] < 7){//小城故事
        TravelCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([TravelCollectionViewCell class]) forIndexPath:indexPath];
        cell.delegate = self;
        cell.modelData = self.travelDataArra[indexPath.row];
        return cell;
    }else {
//        FilmCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([FilmCollectionViewCell class]) forIndexPath:indexPath];
//        cell.modelData = self.filmDataArra[indexPath.row];
        
        FilmCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([FilmCollectionViewCell class]) forIndexPath:indexPath];
        cell.modelData = self.filmDataArra[indexPath.row];
        NSString * transformStr = cell.modelData.filmID;
        NSString * videoURLStr = cell.modelData.vic;
        WS(ws)
        cell.videoBlock = ^(){
            NSLog(@"添加按钮点击事件");
            //        FilmCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([FilmCollectionViewCell class]) forIndexPath:indexPath];
            //        cell.modelData = self.dataArr[indexPath.row];
            NSURL *url = [NSURL URLWithString:videoURLStr];
            AVPlayer *avPlayer= [AVPlayer playerWithURL:url];
            if (@available(iOS 10.0, *)) {
                avPlayer.automaticallyWaitsToMinimizeStalling = NO;
            }
            AVPlayerViewController *playerViewController = [[AVPlayerViewController alloc] init];
            playerViewController.player = avPlayer;
            [[UIViewController getCurrentVC] presentViewController:playerViewController animated:YES completion:nil];
            [playerViewController.player play];
        };
        cell.block = ^(){
            MyFilmCommentListViewController * vc = [[MyFilmCommentListViewController alloc] init];
            vc.did =  [transformStr intValue];
            [self.navigationController pushViewController:vc animated:YES];
        };
        cell.likeBlock = ^(){
            ws.filmID =  [transformStr intValue];
            [self transformLikesDataWithDid:ws.filmID];
        };
        
        
        
        return cell;
    }
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader])
    {
        HotRecommendCollectionReusableView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([HotRecommendCollectionReusableView class]) forIndexPath:indexPath];
        headView.delegate = self;
        headView.isHiddenTitle = self.isHiddenTitle;
        return headView;
    }
    return nil;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    if (self.isHiddenTitle) {
        return CGSizeMake(SCREEN_WIDTH, 50);
    }
    return CGSizeMake(SCREEN_WIDTH, 140);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if ([UserModel isSaveLogin]) {
        if ([self.sign intValue]<6) {
            TravelInforViewController * travelInforVC = [[TravelInforViewController alloc] init];
            HomeCollectionViewCell * cell = (HomeCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([HomeCollectionViewCell class]) forIndexPath:indexPath];
            cell.modelData = self.dataArr[indexPath.row];
            travelInforVC.tid = [cell.modelData.dataId intValue];
            [self.navigationController pushViewController:travelInforVC animated:YES];
        }else if([self.sign intValue]<7) {
            TravelsViewController * vc = [[TravelsViewController alloc] init];
            TravelCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([TravelCollectionViewCell class]) forIndexPath:indexPath];
            cell.modelData = self.travelDataArra[indexPath.row];
            vc.dID = [cell.modelData.travelID intValue];
            [self.navigationController pushViewController:vc animated:YES];
            NSLog(@"其他操作");
        }
    }else{
        [AppHelper showLogin];
    }
    
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    CGFloat labelBottomY = [self getLabelHeightWithText:((VisitorCommentCellModelData *)self.dataArra[indexPath.row]).content width:SCREEN_WIDTH - 20 font:14];
//    if (((VisitorCommentCellModelData *)self.dataArra[indexPath.row]).pic1 != nil && ((VisitorCommentCellModelData *)self.dataArra[indexPath.row]).pic1.length > 0) {
//        return labelBottomY + 180;
//    }
//    return labelBottomY + 80;
//}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.sign intValue]<6)
    {
        return  CGSizeMake(SCREEN_WIDTH/2 -0.5, 180/WIDTH_5S_SCALE);
    }else if ([self.sign intValue]<7){
//        return CGSizeMake(SCREEN_WIDTH, 220/WIDTH_5S_SCALE);
        self.travelModelData = self.travelDataArra[indexPath.row];
         CGFloat labelBottomY = [self getLabelHeightWithText:self.travelModelData.title width:SCREEN_WIDTH - 20 font:14];
        if (SCREEN_HEIGHT < 569) {
            return CGSizeMake(SCREEN_WIDTH, (labelBottomY + 160)/WIDTH_5S_SCALE);
        }
        if (SCREEN_HEIGHT < 668) {
            return CGSizeMake(SCREEN_WIDTH, (labelBottomY + 180)/WIDTH_5S_SCALE);
        }
        else{
            return CGSizeMake(SCREEN_WIDTH, (labelBottomY + 200)/WIDTH_5S_SCALE);
        }
    }
    return CGSizeMake(SCREEN_WIDTH, 260/WIDTH_5S_SCALE);
}

#pragma mark - HotRecommendDelegate
- (void)getButtonNumWithI:(int)i{
    self.rule = i + 1;
    self.topKind = self.rule;
    
    if ([self.sign intValue]<6) {
        [self getHotViewData];
    }else if ([self.sign intValue]<7){
        [self getTravelInforData];
    }else{
        [self getFilmInforData];
    }
}

- (void)getSignNumWith:(int)sign{
    sign = sign + 1;
    self.bottomDiffrence = sign;
    if (sign<6) {
        self.sign = [NSString stringWithFormat:@"%i", sign];
        [self getHotViewData];
    }else if (sign < 7){
        self.sign = [NSString stringWithFormat:@"%i", sign];
        [self getTravelInforData];
    }else if (sign < 8){
        self.sign = [NSString stringWithFormat:@"%i", sign];
        [self getFilmInforData];
    }
    
}

//自适应Lable高度
- (CGFloat)getLabelHeightWithText:(NSString *)text width:(CGFloat)width font: (CGFloat)font
{
    CGRect rect = [text boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]} context:nil];
    return rect.size.height;
}
@end
